﻿using GalaSoft.MvvmLight;
using AzureTracer.Model;
using System.Windows.Data;
using System.Runtime.Serialization;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using AzureTracer.Services;
using Microsoft.Phone.Tasks;
using AzureTracer.Resources;
using GalaSoft.MvvmLight.Ioc;


namespace AzureTracer.ViewModels
{
    
    public class DetailViewModel : ViewModelBase, IDetailViewModel
    {        
        private ILogService _logService;
        private INavigationService _navigationService;
        private IEmailService _emailService;
        
        public LogEntity Log { get; set; }

        public ICommand LoadedCommand { get; private set; }
        public ICommand DeleteCommand { get; private set; }
        public ICommand SendEmailCommand { get; private set; }
        public ICommand SetAsUnreadCommand { get; private set; }

        public DetailViewModel()
            :this(ViewModelLocator.LogService,ViewModelLocator.NavigationService,ViewModelLocator.EmailService) {}

        [PreferredConstructor]
        public DetailViewModel(ILogService logService, INavigationService navigationService, IEmailService emailService)
        {
            _logService = logService;
            _navigationService = navigationService;
            _emailService = emailService;

            LoadedCommand = new RelayCommand(OnLoaded);
            DeleteCommand = new RelayCommand(OnDelete);
            SetAsUnreadCommand = new RelayCommand(OnSetAsUnread);
            SendEmailCommand = new RelayCommand(OnSendEmail);
        }

        private void OnSendEmail()
        {
            string body = string.Format(labels.EmailBody
                , Log.Timestamp ,Log.Role, Log.RoleInstance, Log.Message);
            string subjet = string.Format(labels.EmailSubjet,Log.Level,Log.Role);
            
            _emailService.SendToUnknow(subjet, body);
        }

        private void OnDelete()
        {
            _logService.LogList.Remove(Log);
            _navigationService.Back();
        }

        private void OnLoaded()
        {
            ChangeIsRead(true);
        }

        private void OnSetAsUnread()
        {
            ChangeIsRead( false);
            _navigationService.Back();
        }

        private void ChangeIsRead(bool isRead)
        {
            if (Log != null)
                Log.IsRead = isRead;
        }
    }
}